package com.bailan.foreat.controller;

import com.bailan.foreat.utils.ObjectRESTResult;
import com.bailan.foreat.utils.UploadUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/common")
public class CommonController {


    @RequestMapping("tologin")
//    @ResponseBody
    public String tologin(){
        return "login";
    }


    @RequestMapping("upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile imgFile, HttpServletRequest request, HttpSession session){

        ObjectRESTResult restResult = new ObjectRESTResult();

        // 生成唯一文件名
        String uuid = UUID.randomUUID().toString().trim();
        String filename = imgFile.getOriginalFilename();
        int index=filename.indexOf(".");
        String fileNames= uuid + filename;

        // 调用UploadUtils工具类将图片存放到服务器上
        File fileDir = UploadUtils.getImgDirFile();

        try {
            // 构建真实的文件路径
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileNames);
            System.out.println(newFile.getAbsolutePath());
            imgFile.transferTo(newFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> emp = new HashMap<>();
        emp.put("fileName",fileNames);
        //返回图片名称
        restResult.setReturnObj(emp);
        return fileNames;

    }





}
